;
(function() {
  var flowState = hlUrlUtil.GetQueryString('page') === 'XQ' ? false : true // false为详情页面   true为审核页面
  Array.prototype.removeRepeatBuildingAndFLoor = function() {
    var res = [this[0]];
    for (var i = 1; i < this.length; i++) {
      var repeat = false;
      for (var j = 0; j < res.length; j++) {
        if (this[i].buildingName == res[j].buildingName && this[i].floorNum == res[j].floorNum) {
          repeat = true;
        }
      }
      if (!repeat) {
        res.push(this[i]);
      }
    }
    return res;
  };

  function toDou(num) {
    return num < 10 ? '0' + num : '' + num;
  }
  function time(oldTime) {
    // 此刻的时间
    if (!oldTime) return '00天00小时';
    var oDate = new Date();
    var iS = parseInt(((oDate.getTime() + 8 * 60 * 60 * 1000) - oldTime) / 1000);
    var iD = parseInt(iS / 86400); // 天数
    iS %= 86400; // 转换成天数剩余的秒数 -> 小时
    var iH = parseInt(iS / 3600); // 小时
    iS %= 3600; // 转换成小时数剩余的秒数 -> 分钟
    var iM = parseInt(iS / 60); // 分钟
    iS %= 60; // 秒数
    return toDou(iD) + '天' + toDou(iH) + '小时'
  }

  new Vue({
    el: '#withdrawFLow',
    data: {
      nav: [{
          name: '意向信息',
          iscur: true
        },
        {
          name: '流程信息',
          iscur: false
        },
        {
          name: '相关文件',
          iscur: false
        },
      ],
      loadWithdrawMesModule: true,
      loadFlowMesModule: false,
      loadxdFlowMesModule: false,
      flowState: flowState, //  判断显示的页面  false为详情页面   true为审核页面
      data: {zlfInfo: {},projectInfo:{stops:[]}},
      auditState: '', // 审核状态
      contratdata: {
        st: [],
        ot: []
      },
      contractFile: [],
      bpmId: hlUrlUtil.GetQueryString('bpmId'),
      taskId: hlUrlUtil.GetQueryString('taskId'),
      userid: JSON.parse(window.localStorage.getItem('userMes')).id,
      projectIds: hlUrlUtil.GetQueryString('projectIds'),
      withdrawId: hlUrlUtil.GetQueryString('businessId'),
      contractId: null,
      matterActive: [],
      bpm: {}, // 工作流程信息
      flowNode: [], // 流程节点
      bpmList: [], // 工作流程列表
      currentNode: [], // 当前处理节点
      st: [], // 车位
      wp: [], // 工位
      stTotalNum: 0, // 车位总数
      wpTotalNum: 0, // 工位总数
      totalArea: 0, // 单元总面积
      building: [], // 楼宇信息
      projectName: null, // 项目名
      unitOpenFlag: true,
      wpOpenFlag: true,
      stOpenFlag: true,
      unitId: null,
      unitDetailsFlag: false,
      approveFlag: null
    },
    filters: {
      dateTime (time) {
        if (!time) return '--';
        return hlDateUtil.formatUTCDate(time, 'yyyy-MM-dd HH:mm:ss')
      },
      dateTimeYYmmDD (time) {
        if (!time) return '--';
        return hlDateUtil.formatUTCDate(time, 'yyyy-MM-dd')
      },
      formatDate: function(time) {
        if (time === undefined) {
          return '--'
        }
        var date = new Date(time)
        return hlDateUtil.formatUTCDate(date, 'yyyy-MM-dd')
      },
      formatDetailDate: function(time) {
        if (time === undefined) return '--'
        return hlDateUtil.formatUTCDate(time)
      },
      formatUndefined: function(item) {
        if (item == undefined) return '--'
        return item
      },
      auditState: function(state) {
        return hlCodeConvert.withdrawAuditState(state)
      },
      formatNum: function(item) {
        return hlNumberUtil.formatNum(item)
      },
      timeDifference: function(item) {
        return
      }
    },
    methods: {
      //催办
      cuiban: function() {
        var self = this;
        hlhttp.get({
          url: 'bpm/urge/time',
          data: {
            bpm_id: self.bpmId
          },
          success: function(res) {
            hllayer.promptSm({
              title: '催办',
              leftBtn: '确定',
              subTitle: '本操作将给处理人发送一条微信消息！',
              tips: '距离上次催办' + time(res.time),
              confirm: function(msg) {
                hlhttp.put({
                  url: 'bpm/urge',
                  data: {
                    bpm_id: self.bpmId,
                    task_id: self.taskId,
                    memo: msg || '#'
                  },
                  success: function() {
                    hl.toast('发送成功')
                    $('.hllayer-prompt,.hllayer-mask').remove()
                    self.getData()
                    self.getBpmDetailData()
                    self.getBpmListData()
                  }
                })
              }
            })
          }
        })
      },
      //tab切换
      switchNav: function(item, index) {
        var self = this
        this.nav.map(function(_item, _i) {
          _i == index ? _item.iscur = true : _item.iscur = false;
        })
        if (index == 0) {
          self.loadWithdrawMesModule = true
          self.loadFlowMesModule = false
          this.loadxdFlowMesModule = false
        }
        if (index == 1) {
          self.loadWithdrawMesModule = false
          self.loadFlowMesModule = true
          this.loadxdFlowMesModule = false
        }
        if (index == 2) {
          self.loadWithdrawMesModule = false
          self.loadFlowMesModule = false
          this.loadxdFlowMesModule = true
        }
      },
      // 单元数据去重整合处理
      dealWithUnitData: function(unitsData) {
        // 单元
        // 去除含有工位车位的单元
        var units = [];
        unitsData.map(function(_item) {
          if (_item.positions.length === 0) {
            units.push(_item)
          }
        })
        if (units.length === 0) {
          return {
            building: [],
            totalArea: 0
          }
        }
        // 合并单元项
        var unit = [];
        var totalArea = 0;
        for (var i = 0; i < units.length; i++) {
          unit.push({
            buildingName: units[i].buildingName,
            floorNum: units[i].floorNum,
            floorName: units[i].floorName,
            unit: [],
            unitId: []
          })
        }
        var unitArr = unit.removeRepeatBuildingAndFLoor()
        for (var z = 0; z < unitArr.length; z++) {
          for (var m = 0; m < units.length; m++) {
            if (units[m].buildingName == unitArr[z].buildingName && units[m].floorNum == unitArr[z].floorNum) {
              unitArr[z].unit.push(units[m].unitName + '(' + hlNumberUtil.formatNum(units[m].unitAcreage) + 'm²)')
              unitArr[z].unitId.push(units[m].unitId)
              totalArea = totalArea + Number(units[m].unitAcreage)
            }
          }
        }
        // 合并楼层项
        var building = [];
        for (var j = 0; j < unitArr.length; j++) {
          building.push({
            buildingName: unitArr[j].buildingName,
            floor: []
          })
        }
        var buildingArr = hlArrayUtil.removeRepeat(building, 'buildingName')
        for (var k = 0; k < buildingArr.length; k++) {
          for (var n = 0; n < unitArr.length; n++) {
            if (unitArr[n].buildingName == buildingArr[k].buildingName) {
              buildingArr[k].floor.push({
                'floorNum': unitArr[n].floorNum,
                'floorName': unitArr[n].floorName,
                'unit': unitArr[n].unit,
                'unitId': unitArr[n].unitId
              })
            }
          }
        }
        return {
          building: buildingArr,
          totalArea: totalArea
        }
      },
      // 获取单元详情
      getUnitDetails: function(unitId) {
        var self = this;
        self.unitId = unitId;
        self.unitDetailsFlag = true;
      },
      // 关闭单元详情弹出层
      closeUnitPop: function(state) {
        this.unitId = null;
        this.unitDetailsFlag = false;
      },
      // 查看出租资源详情信息
      checkDetailMes: function(type) {
        var self = this;
        if (type === 'unit') {
          if (self.unitOpenFlag === true) {
            self.unitOpenFlag = false
            return false
          }
          if (self.unitOpenFlag === false) {
            self.unitOpenFlag = true
            return false
          }
        }
        if (type === 'wp') {
          if (self.wpOpenFlag === true) {
            self.wpOpenFlag = false;
            return false;
          }
          if (self.wpOpenFlag === false) {
            self.wpOpenFlag = true
            return false;
          }
        }
        if (type === 'st') {
          if (self.stOpenFlag === true) {
            self.stOpenFlag = false
            return false;
          }
          if (self.stOpenFlag === false) {
            self.stOpenFlag = true
            return false;
          }
        }
      },
      // 获取意向数据
      getData: function() {
        var _this = this;
        hlhttp.get({
          url: 'contract/intent',
          data: {
            id: _this.withdrawId
          },
          success: function(res) {
            _this.auditState = res.auditStatusCode
            _this.contractId = res.contractId
            if (res.auditStatusCode != 'WCP' && res.auditStatusCode != 'WBP') {
              // $('.audit-pass').hide()
              // $('.audit-no-pass').hide()
            }
            _this.data = res
            _this.hireCauseActive = res.reason
            _this.todoList = res.todoList
            // contract.formatUnitData(res.contractId, function(data) {
            //   _this.contratdata = data;
            // })
          }
        })
      },
      //大图
      bigPicShow: function(arr, i) {
        $.imageShow(arr, i)
      },
      //审核通过
      passAudit: function() {
        var self = this;
        var auditState = self.auditState; // WBP 待业务审核 WCP 待财务审核 FBP 业务审核不通过 FCP 财务审核失败
        var sendBusinessAuditPassRequest = function(mes) {
          hlhttp.put({
            url: 'bpm/_pass',
            data: {
              bpm_key: 'IT',
              task_id: self.taskId,
              bpm_id: self.bpmId,
              memo: mes || '#',
							state: self.auditState
            },
            success: function(data) {
              hl.toast('审核通过')
              hllayer.close();
              hlUrlUtil.goTo('todo', {
                stateName: 'IT',
                projectIds: self.projectIds,
                ddtab: true
              })
            }
          })
        }
        var sendFinancialAuditPassRequest = function(mes) {
          hlhttp.put({
            url: 'bpm/_pass',
            data: {
              bpm_key: 'IT',
              task_id: self.taskId,
              bpm_id: self.bpmId,
              memo: mes || '#',
							state: self.auditState
            },
            success: function(data) {
              hl.toast('审核通过')
              hllayer.close();
              hlUrlUtil.goTo('todo', {
                stateName: 'IT',
                projectIds: self.projectIds,
                ddtab: true
              })
            }
          })
        }
        hllayer.prompt({
          title: '审核通过', // 标题  默认为空
          placeholder: '审核通过原因说明（非必填）',
          leftBtn: '提交',
          confirm: function(mes) {
            if (auditState == 'WA') sendBusinessAuditPassRequest(mes)
            if (auditState == 'WA') sendFinancialAuditPassRequest(mes)
          }
        })
      },
      //审核不通过
      notPassAudit: function() {
        var self = this;
        var auditState = self.auditState;
        var sendBusinessAuditNotPassRequest = function(mes) {
          hlhttp.put({
            url: 'bpm/_reject',
            data: {
              task_id: self.taskId,
              bpm_id: self.bpmId,
              memo: mes || '#',
							state: self.auditState
            },
            success: function(data) {
              hl.toast('审核不通过')
              hllayer.close();
              hlUrlUtil.goTo('todo', {
                stateName: 'IT',
                projectIds: self.projectIds,
                ddtab: true
              })
            }
          })
        }
        var sendFinancialAuditNotPassRequest = function(mes) {
          hlhttp.put({
            url: 'bpm/_reject',
            data: {
              task_id: self.taskId,
              bpm_id: self.bpmId,
              memo: mes || '#',
							state: self.auditState
            },
            success: function(data) {
              hl.toast('审核不通过')
              hllayer.close();
              hlUrlUtil.goTo('todo', {
                stateName: 'IT',
                projectIds: self.projectIds,
                ddtab: true
              })
            }
          })
        }
        hllayer.prompt({
          title: '审核不通过',
          placeholder: '审核不通过原因说明（必填）',
          leftBtn: '提交',
          confirm: function(mes) {
            if (!mes) {
              hl.toast('请填写审核不通过原因')
              return
            }
            if (auditState == 'WA') sendBusinessAuditNotPassRequest(mes)
            if (auditState == 'WA') sendFinancialAuditNotPassRequest(mes)
          }
        })
      },
      // 获取流程详情数据
      getBpmDetailData: function() {
        var self = this;
        hlhttp.get({
          url: 'bpm',
          data: {
            bpm_key: 'WT',
            bpm_id: self.bpmId
          },
          success: function(data) {
            var newArr = data;
            var bpdefId = data.bpdefId || 0;

            self.approveFlag = data.approveFlag
            self.$set(self.$data, 'bpm', newArr)
            self.getFlowNodeData(bpdefId)

            if (data.state == 'FN' || data.state == 'DL') {
              $('.audit-pass').hide()
              $('.audit-no-pass').hide()
            }
          }
        })
      },
      // 获取流程节点数据
      getFlowNodeData: function(id) {
        var self = this;
        // 当所传id为0时展示最初始的业务节点图   ====>  开始 ----- 业务审核 ----- 财务审核  ----- 结束
        if (id == 0) {
          var nodeData = [{
            name: '业务审核'
          }, {
            name: '财务审核'
          }]
          self.flowNode = nodeData;
        }
        if (id != 0) {
          hlhttp.get({
            url: 'bpdef_phases',
            data: {
              'bpdef_id': id
            },
            success: function(data) {
              self.flowNode = data
            }
          })
        }
      },
      // 获取工作流程任务列表数据
      getBpmListData: function() {
        var self = this;
        hlhttp.get({
          url: 'bpm/tasks',
          data: {
            bpm_id: self.bpmId
          },
          success: function(data) {
            var newArr = [];
            for (var i = 0; i < data.length; i++) {
              if (data[i]['endTime']) {
                newArr.push(data[i]);
              }
            }
            self.$set(self.$data, 'bpmList', newArr)
          }
        })
      },
      //撤回
      withdrawCH: function() {
        var self = this;
        hllayer.confirm('撤回后，流程将立即终止', function() {
          hlhttp.delete({
            url: 'bpm/_withdraw?bpm_id=' + self.bpmId,
            success: function() {
              hl.toast('撤回成功')
              hlUrlUtil.goTo('myFlowList', {
                projectIds: self.projectIds,
                ddtab: true
              })
            }
          })
        })
      },
      //计算时间差
      calculateTimeDifference: function(item1, item2) {
        return hlDateUtil.timeDifference(item1, item2)
      },
      previewImage: function(url) {
        var imageExt = ['jpg', 'jpeg', 'png', 'JPG', 'JPEG', 'PNG'];
        var pdfExt = ['pdf', 'PDF'];
        var officeExt = ['docx','doc','xlsx','xls','xlt']
        var imageFlag = false;
        var pdfFlag = false;
        var officeFlag = false;

        imageExt.forEach((e, i) => {
          if (url.indexOf(e) !== -1) imageFlag = true;
        })
        if (imageFlag) {
          $.imageShow([url])
        }
        pdfExt.forEach((e, i) => {
          if (url.indexOf(e) !== -1) pdfFlag = true;
        })
        if (pdfFlag) {
          $.previewPDF(url)
        }

        officeExt.forEach((e, i) => {
          if (url.indexOf(e) !== -1) officeFlag = true
        })
        if (officeFlag) {
          $.previewOffice(url)
        }

      }
    },
    computed: {
      unitList () {
        let result = [];
        if (this.data.intentType == 'ER') {
          let data = this.data.projectInfo.units;
          if (!data.length) return [];
          let buildinglist = hlArrayUtil.removeRepeat(data, 'buildingId')
          buildinglist.map(item => {
            result.push({
              projectName: this.data.projectInfo.projectName,
              projectId: this.data.projectInfo.projectId,
              buildingName: item.buildingName,
              buildingId: item.buildingId,
              floor: item.floorNum,
              floorId: item.floorId,
              children: []
            })
          })
          data.map(item => {
            result.map(item0 => {
              if (item.floorId == item0.floorId) {
                item0.children.push({unitName: item.unitName, unitId: item.unitId, acreage: item.unitAcreage})
              }
            })
          })
        }
        return result
      },
      wplist () {
        let result = [];
        if (this.data.intentType == 'WR') {
          let data = this.data.projectInfo.wps;
          if (!data.length) return [];
          let buildinglist = hlArrayUtil.removeRepeat(data, 'unitId')
          buildinglist.map(item => {
            result.push({
              projectName: this.data.projectInfo.projectName,
              projectId: this.data.projectInfo.projectId,
              buildingName: item.buildingName,
              buildingId: item.buildingId,
              floor: item.floorNum,
              floorNum: item.floorNum,
              floorId: item.floorId,
              unitId: item.unitId,
              unitName: item.unitName,
              children: []
            })
          })
          data.map(item => {
            result.map(item0 => {
              if (item.unitId == item0.unitId) {
                item0.children.push({wpName: item.wpName, wpId: item.wpId})
              }
            })
          })
        }
        return result
      },
      stlist () {
        let result = [];
        if (this.data.projectInfo.stops.length) {
          let data = this.data.projectInfo.stops;
          if (!data.length) return [];
          let buildinglist = hlArrayUtil.removeRepeat(data, 'unitId')
          buildinglist.map(item => {
            result.push({
              projectName: this.data.projectInfo.projectName,
              projectId: this.data.projectInfo.projectId,
              buildingName: item.buildingName,
              buildingId: item.buildingId,
              floor: item.floorNum,
              floorId: item.floorId,
              unitId: item.unitId,
              unitName: item.unitName,
              children: []
            })
          })
          data.map(item => {
            result.map(item0 => {
              if (item.unitId == item0.unitId) {
                item0.children.push({stopName: item.stopName, stopId: item.stopId})
              }
            })
          })
        }
        return result
      },
      stCount () {
        let count = 0;
        if (this.stlist.length) {
          this.stlist.map(item => {
            count += item.children.length
          })
        }
        return count
      },
      wpCount () {
        let count = 0;
        if (this.wplist.length) {
          this.wplist.map(item => {
            count += item.children.length
          })
        }
        return count
      },
      unitCount () {
        let count = 0;
        if (this.unitList.length) {
          this.unitList.map(item => {
            item.children.map(single =>{
              count += Number(single.acreage)
            })
          })
        }
        return count
      }
    },
    mounted: function() {
      this.getData()
      this.getBpmDetailData()
      this.getBpmListData()
    }
  })
}())
